package com.mapforge.selection;

import java.awt.Point;

/**
 * The default implementation of interface {@link SelectionModifier}. This
 * abstract class tracks whether the modifier is modifying from center, and
 * allows implementing classes to control how the final selection is made.
 * 
 * @author Will Morrison
 * 
 */
public abstract class AbstractSelectionModifier implements SelectionModifier {
	private boolean modifyFromCenter;

	@Override
	public boolean isModifyingFromCenter() {
		return this.modifyFromCenter;
	}

	@Override
	public void setModifyingFromCenter(boolean centerModify) {
		this.modifyFromCenter = centerModify;
	}

	/**
	 * This method modifies 2 points by translating their x locations negatively
	 * by half the difference their x coordinates, and their y locations
	 * negatively by half the difference of their y coordinates. This ensures
	 * the difference between the 2 points will be as equal as possible.
	 * 
	 * @param anchorPoint
	 * @param movingPoint
	 */
	protected void modifyFromCenter(Point anchorPoint, Point movingPoint) {
		int dx = Math.abs(anchorPoint.x - movingPoint.x);
		int dy = Math.abs(anchorPoint.y - movingPoint.y);
		if (movingPoint.x > anchorPoint.x) {
			anchorPoint.x -= dx;
		} else {
			anchorPoint.x += dx;
		}
		if (movingPoint.y > anchorPoint.y) {
			anchorPoint.y -= dy;
			//movingPoint.y += dy;
		} else {
			anchorPoint.y += dy;
			//movingPoint.y -= dy;
		}
	}

	@Override
	public final void modifySelection(Point startPoint, Point currentPoint) {
		doModify(startPoint, currentPoint);
		if (isModifyingFromCenter()) {
			modifyFromCenter(startPoint, currentPoint);
		}
	}

	/**
	 * Points should be modified in this method.
	 * 
	 * @param startPoint
	 * @param currentPoint
	 */
	public abstract void doModify(Point startPoint, Point currentPoint);
}
